package com.wqz.day.day.up.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.wqz.day.day.up.dto.selenium.BaseResultDto;
import com.wqz.day.day.up.dto.selenium.creditScore.CreditScoreDimensionListDto;
import com.wqz.day.day.up.dto.selenium.creditScore.CreditScoreDto;
import com.wqz.day.day.up.enums.CreditScoreDimensionEnum;
import com.wqz.day.day.up.enums.WebDriverQueueEnum;
import com.wqz.day.day.up.exception.CustomException;
import com.wqz.day.day.up.queue.DecorationWebDriver;
import com.wqz.day.day.up.queue.WebDriverQueue;
import com.wqz.day.day.up.utils.DateUtils;
import com.wqz.day.day.up.vo.DimensionItemVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * This is a class template with author information.
 *
 * @author wuqz
 * @date 2024/3/4
 */
@Service
@Slf4j
public class CreditScoreService {

    /**
     * chromeDriver驱动地址
     */
    @Value("${selenium.chrome.driver.path}")
    private String chromeDriverPath;

    /**
     * selenium截屏地址
     */
    @Value("${aliyun.oss.path.seleninum}")
    private String seleniumChromeScreenShotPath;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${server.port}")
    private String serverPort;


    @Qualifier("webDriverQueue")
    @Autowired
    WebDriverQueue webDriverQueue;


    /**
     * 返回信用分详情页面
     * @param keyNo
     * @return
     */
    public ModelAndView getCreditScoreDetail(String keyNo) throws IOException {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("credit-score");

            String json = "{\n" +
                    "    \"Status\": 200,\n" +
                    "    \"Result\": {\n" +
                    "        \"Id\": \"b425dcf2a602089fb8b00d55890e5046\",\n" +
                    "        \"Score\": 1162,\n" +
                    "        \"ScoreDesc\": \"\",\n" +
                    "        \"ScoreLevel\": \"L-12\",\n" +
                    "        \"ScoreDescInfo\": \"L-12 信用表现卓越，当前处于良性循环状态，违约风险很低\",\n" +
                    "        \"ChangeTips\": \"\",\n" +
                    "        \"UpdateDate\": 1710950400,\n" +
                    "        \"IndustryAnalysis\": {\n" +
                    "            \"AvgScore\": 633,\n" +
                    "            \"CompanyCount\": 5991,\n" +
                    "            \"CompanyCountWithUnit\": 0.6,\n" +
                    "            \"IndustryDesc\": \"汽车制造业\",\n" +
                    "            \"ProvinceDesc\": \"广西\",\n" +
                    "            \"Rank\": 1\n" +
                    "        },\n" +
                    "        \"AnalysisReason\": \"\",\n" +
                    "        \"CompanyInfo\": {\n" +
                    "            \"Name\": \"广西汽车集团有限公司\",\n" +
                    "            \"KeyNo\": \"b425dcf2a602089fb8b00d55890e5046\",\n" +
                    "            \"ImageUrl\": \"https://image.qcc.com/logo/b425dcf2a602089fb8b00d55890e5046.jpg?x-oss-process=style/logo_120\",\n" +
                    "            \"Status\": \"存续\",\n" +
                    "            \"StartDate\": 632678400,\n" +
                    "            \"RegistCapi\": \"108289.312849万元人民币\",\n" +
                    "            \"Oper\": {\n" +
                    "                \"Org\": 2,\n" +
                    "                \"Name\": \"韦宏文\",\n" +
                    "                \"KeyNo\": \"p801d9f10db71ad007f8334c8f4ab2c5\",\n" +
                    "                \"HasImage\": true,\n" +
                    "                \"CompanyCount\": 6,\n" +
                    "                \"OperType\": 1\n" +
                    "            },\n" +
                    "            \"TagsInfoV2\": [\n" +
                    "                {\n" +
                    "                    \"Type\": 905,\n" +
                    "                    \"Name\": \"发票抬头\",\n" +
                    "                    \"ShortName\": null,\n" +
                    "                    \"DataExtend\": \"\",\n" +
                    "                    \"TradingPlaceCode\": null,\n" +
                    "                    \"TradingPlaceName\": null,\n" +
                    "                    \"DataExtend2\": null\n" +
                    "                },\n" +
                    "                {\n" +
                    "                    \"Type\": 903,\n" +
                    "                    \"Name\": \"存续\",\n" +
                    "                    \"ShortName\": null,\n" +
                    "                    \"DataExtend\": \"\",\n" +
                    "                    \"TradingPlaceCode\": null,\n" +
                    "                    \"TradingPlaceName\": null,\n" +
                    "                    \"DataExtend2\": null\n" +
                    "                },\n" +
                    "                {\n" +
                    "                    \"Type\": 99,\n" +
                    "                    \"Name\": \"曾用名\",\n" +
                    "                    \"ShortName\": null,\n" +
                    "                    \"DataExtend\": \"柳州五菱汽车有限责任公司\",\n" +
                    "                    \"TradingPlaceCode\": null,\n" +
                    "                    \"TradingPlaceName\": null,\n" +
                    "                    \"DataExtend2\": null\n" +
                    "                },\n" +
                    "                {\n" +
                    "                    \"Type\": 505,\n" +
                    "                    \"Name\": \"小微企业\",\n" +
                    "                    \"ShortName\": \"\",\n" +
                    "                    \"DataExtend\": \"\",\n" +
                    "                    \"TradingPlaceCode\": null,\n" +
                    "                    \"TradingPlaceName\": null,\n" +
                    "                    \"DataExtend2\": null\n" +
                    "                },\n" +
                    "                {\n" +
                    "                    \"Type\": 622,\n" +
                    "                    \"Name\": \"省管国企\",\n" +
                    "                    \"ShortName\": \"\",\n" +
                    "                    \"DataExtend\": \"\",\n" +
                    "                    \"TradingPlaceCode\": \"\",\n" +
                    "                    \"TradingPlaceName\": \"\",\n" +
                    "                    \"DataExtend2\": null\n" +
                    "                },\n" +
                    "                {\n" +
                    "                    \"Type\": 88,\n" +
                    "                    \"Name\": \"企业技术中心\",\n" +
                    "                    \"ShortName\": \"\",\n" +
                    "                    \"DataExtend\": \"{\\\"p\\\":\\\"\\\",\\\"bd\\\":1040572800,\\\"s\\\":\\\"2002年  国家认定的企业技术中心名单\\\",\\\"file\\\":\\\"\\\",\\\"c\\\":\\\"T_TC\\\",\\\"pd\\\":1040572800,\\\"is\\\":1,\\\"sn\\\":110,\\\"l\\\":1,\\\"ed\\\":0,\\\"ds\\\":1}\",\n" +
                    "                    \"TradingPlaceCode\": \"\",\n" +
                    "                    \"TradingPlaceName\": \"\",\n" +
                    "                    \"DataExtend2\": null\n" +
                    "                },\n" +
                    "                {\n" +
                    "                    \"Type\": 90,\n" +
                    "                    \"Name\": \"技术创新示范企业\",\n" +
                    "                    \"ShortName\": \"\",\n" +
                    "                    \"DataExtend\": \"{\\\"p\\\":\\\"\\\",\\\"bd\\\":1704988800,\\\"s\\\":\\\"通过2023年复核评价的国家技术创新示范企业名单\\\",\\\"file\\\":\\\"https://qccdata.qichacha.com/TechnologyCompany/f599ae49cd612cdaa07adc741ee5de51.doc\\\",\\\"c\\\":\\\"T_TD\\\",\\\"pd\\\":1704988800,\\\"is\\\":1,\\\"sn\\\":130,\\\"l\\\":1,\\\"ed\\\":1799683200,\\\"ds\\\":1}\",\n" +
                    "                    \"TradingPlaceCode\": \"\",\n" +
                    "                    \"TradingPlaceName\": \"\",\n" +
                    "                    \"DataExtend2\": null\n" +
                    "                },\n" +
                    "                {\n" +
                    "                    \"Type\": 92,\n" +
                    "                    \"Name\": \"众创空间\",\n" +
                    "                    \"ShortName\": \"\",\n" +
                    "                    \"DataExtend\": \"{\\\"p\\\":\\\"\\\",\\\"bd\\\":1616083200,\\\"s\\\":\\\"2020年度国家备案众创空间复核结果\\\",\\\"file\\\":\\\"https://qccdata.qichacha.com/TechnologyCompany/1d7c8abf13a230c18b09209c33888f15.pdf\\\",\\\"c\\\":\\\"T_MS\\\",\\\"pd\\\":1616083200,\\\"is\\\":1,\\\"sn\\\":150,\\\"l\\\":1,\\\"ed\\\":0,\\\"ds\\\":1}\",\n" +
                    "                    \"TradingPlaceCode\": \"\",\n" +
                    "                    \"TradingPlaceName\": \"\",\n" +
                    "                    \"DataExtend2\": null\n" +
                    "                }\n" +
                    "            ]\n" +
                    "        },\n" +
                    "        \"DimensionOverView\": [\n" +
                    "            \"经营状况\",\n" +
                    "            \"企业背景\"\n" +
                    "        ],\n" +
                    "        \"DimensionList\": [\n" +
                    "            {\n" +
                    "                \"Type\": \"QYBJ\",\n" +
                    "                \"TypeDesc\": \"企业背景\",\n" +
                    "                \"Score\": 95,\n" +
                    "                \"ScoreDesc\": \"优秀\",\n" +
                    "                \"GoodLabels\": [\n" +
                    "                    \"小微企业\",\n" +
                    "                    \"省管国企\",\n" +
                    "                    \"成熟型企业\",\n" +
                    "                    \"大型集团核心成员\",\n" +
                    "                    \"较高市场份额\",\n" +
                    "                    \"成立超过15年\",\n" +
                    "                    \"注册资本超半数同行企业\"\n" +
                    "                ],\n" +
                    "                \"BadLabels\": [],\n" +
                    "                \"PromptLabels\": [],\n" +
                    "                \"SpecialText\": \"进入市场时期早、业务受政策支持、股东实力雄厚且股权结构较稳定的企业，往往信用评估结果较好。\"\n" +
                    "            },\n" +
                    "            {\n" +
                    "                \"Type\": \"LYLS\",\n" +
                    "                \"TypeDesc\": \"履约历史\",\n" +
                    "                \"Score\": 59,\n" +
                    "                \"ScoreDesc\": \"中等\",\n" +
                    "                \"GoodLabels\": [\n" +
                    "                    \"公开数据层面履约表现较好\"\n" +
                    "                ],\n" +
                    "                \"BadLabels\": [],\n" +
                    "                \"PromptLabels\": [],\n" +
                    "                \"SpecialText\": \"商业场景、融资场景及司法场景的公开数据均是企业信用行为的记录，更多的守约行为有助于企查分提升。\"\n" +
                    "            },\n" +
                    "            {\n" +
                    "                \"Type\": \"GLSP\",\n" +
                    "                \"TypeDesc\": \"管理水平\",\n" +
                    "                \"Score\": 70,\n" +
                    "                \"ScoreDesc\": \"良好\",\n" +
                    "                \"GoodLabels\": [\n" +
                    "                    \"连续三年公示年报\",\n" +
                    "                    \"无劳动纠纷或仲裁记录\",\n" +
                    "                    \"无经营异常记录\"\n" +
                    "                ],\n" +
                    "                \"BadLabels\": [],\n" +
                    "                \"PromptLabels\": [],\n" +
                    "                \"SpecialText\": \"合规经营、较少涉及诉讼、处罚、经营异常等负面事件且投融资规模合理的企业，往往信用评估结果较好。\"\n" +
                    "            },\n" +
                    "            {\n" +
                    "                \"Type\": \"ZZPJ\",\n" +
                    "                \"TypeDesc\": \"资质评价\",\n" +
                    "                \"Score\": 84,\n" +
                    "                \"ScoreDesc\": \"优秀\",\n" +
                    "                \"GoodLabels\": [\n" +
                    "                    \"企业技术中心\",\n" +
                    "                    \"技术创新示范企业\",\n" +
                    "                    \"众创空间\",\n" +
                    "                    \"荣获国家级荣誉\",\n" +
                    "                    \"资质证书丰富多元\",\n" +
                    "                    \"质量管理体系认证\"\n" +
                    "                ],\n" +
                    "                \"BadLabels\": [],\n" +
                    "                \"PromptLabels\": [],\n" +
                    "                \"SpecialText\": \"监管评价、资质认证、荣誉称号等因素能够彰显企业的行业地位和声誉，对信用评估有积极影响。\"\n" +
                    "            },\n" +
                    "            {\n" +
                    "                \"Type\": \"JYZK\",\n" +
                    "                \"TypeDesc\": \"经营状况\",\n" +
                    "                \"Score\": 98,\n" +
                    "                \"ScoreDesc\": \"优秀\",\n" +
                    "                \"GoodLabels\": [\n" +
                    "                    \"招标项目较多\",\n" +
                    "                    \"科技成果丰硕\",\n" +
                    "                    \"国标制定参与者\",\n" +
                    "                    \"拥有发明专利\",\n" +
                    "                    \"专利库充盈\"\n" +
                    "                ],\n" +
                    "                \"BadLabels\": [],\n" +
                    "                \"PromptLabels\": [],\n" +
                    "                \"SpecialText\": \"纳税、招投标、财务、科技创新等维度的表现能够反映企业的稳健运营能力和持续发展潜力，对信用评估有积极影响。\"\n" +
                    "            }\n" +
                    "        ]\n" +
                    "    }\n" +
                    "}";
            BaseResultDto<CreditScoreDto> resultDto = JSONObject.parseObject(json, new TypeReference<BaseResultDto<CreditScoreDto>>(){});

            //解析dimension,并添加至视图数据属性中
            dealDimensionItemVo(resultDto.getResult(), modelAndView);

            //分数
            modelAndView.getModel().put("score", Integer.valueOf(resultDto.getResult().getScore()));

            //等级
            modelAndView.getModel().put("scoreLevel", resultDto.getResult().getScoreLevel());

            //等级描述
            modelAndView.getModel().put("scoreDescInfo", resultDto.getResult().getScoreDescInfo());

            //更新日期  时间戳转换成yyyy年MM月dd日
            Long updateTimestamp = resultDto.getResult().getUpdateDate();
            String updateDate = convertDateStrByTimeStamp(updateTimestamp * 1000, "yyyy年MM月dd日");
            modelAndView.getModel().put("updateDate", updateDate + " 更新");

            //雷达维度
            modelAndView.getModel().put("dimensionListForRadar", JSONObject.toJSONString(resultDto.getResult().getDimensionList()));

            //行业描述  需要特殊出下直辖市
            if (resultDto.getResult().getIndustryAnalysis() != null) {
                String provinceDesc = dealProvinceDesc(resultDto.getResult().getIndustryAnalysis().getProvinceDesc());
                resultDto.getResult().getIndustryAnalysis().setProvinceDesc(provinceDesc);
            }
            modelAndView.getModel().put("industryAnalysis", resultDto.getResult().getIndustryAnalysis());


        return modelAndView;
    }

    /**
     * 解析维度
     * @param creditScoreDto
     * @return
     */
    public void dealDimensionItemVo(CreditScoreDto creditScoreDto, ModelAndView modelAndView) {
        //取出维度信息
        List<CreditScoreDimensionListDto> dimensionList = creditScoreDto.getDimensionList();

        if(CollectionUtils.isEmpty(dimensionList)) {
            return;
        }

        Map<String, CreditScoreDimensionEnum> creditScoreDimensionEnumMap = CreditScoreDimensionEnum.creditScoreDimensionEnumMap();

        for (CreditScoreDimensionListDto dto : dimensionList) {
            DimensionItemVo dimensionItemVo = new DimensionItemVo();
            //名字
            dimensionItemVo.setName(dto.getTypeDesc());

            //处理蓝色标签
            dimensionItemVo.setGoodTags(dto.getGoodLabels());

            //处理红色标签
            dimensionItemVo.setBadTags(dto.getBadLabels());

            //处理黄色标签
            dimensionItemVo.setProptTags(dto.getPromptLabels());

            //处理描述
            dimensionItemVo.setDesc(dto.getSpecialText());

            //处理视图数据中key
            CreditScoreDimensionEnum creditScoreDimensionEnum = creditScoreDimensionEnumMap.get(dimensionItemVo.getName());

            modelAndView.getModel().put(creditScoreDimensionEnum.getCode(), dimensionItemVo);
        }
    }


    public List<String> dealScoreStat(Integer score) {
        /** 均分10等分：最大10颗半星即满5星 */
        int allHalfStars = (int) Math.floor(score / 10) + 1;
        /** 满星数 */
        int stars = allHalfStars / 2;
        /** 半星数 */
        int halfStar = allHalfStars % 2;

        List<String> arr = new ArrayList<String>();
        for (int i = 0; i < 5; i++) {
            if (i + 1 <= stars) {
                arr.add( "1");
            } else if (i == stars && halfStar > 0) {
                arr.add( "0.5");
            } else {
                arr.add( "0");
            }
        }

        return arr;
    }


    public String getCreditScoreDetailImg(String keyNo, WebDriverQueueEnum webDriverQueueEnum, String type) {
        String uuid = IdUtil.fastUUID();
        log.info("CreditScoreService-getCreditScoreDetailImg-{}：开始截取keyNo[{}]的图片[{}]######", uuid, keyNo, webDriverQueueEnum.getCode());

        //使用日期归档  20240306
        String dateStr = DateUtils.format(new Date(), "yyyy-MM-dd");
        String fileName = uuid + ".png";
        String folder = String.format(seleniumChromeScreenShotPath, dateStr);

        DecorationWebDriver decorationWebDriver = null;

        try {
            //获取正确的截图尺寸
            Dimension dimension = getDimension(webDriverQueueEnum, keyNo);

            if (dimension == null) {
                throw new CustomException("获取尺寸信息异常！");
            }

            decorationWebDriver =  webDriverQueue.dequeue();
            WebDriver webDriver = decorationWebDriver.getWebDriver();
            //获取不同需求的截图尺寸
            webDriver.manage().window().setSize(dimension);

            // 打开网页
            String htmlUrl = String.format("http://localhost:%s%s/creditScore/%s?", serverPort, contextPath, type);
            webDriver.get(htmlUrl + "keyNo=" + keyNo);

            //根据结束值判断页面加载完毕
            WebElement webElement = webDriver.findElement(By.className("end-page"));

            WebDriverWait webDriverWait = new WebDriverWait(webDriver, 5);
            webDriverWait.until(ExpectedConditions.textToBePresentInElement(webElement, "true"));

            JavascriptExecutor jse= (JavascriptExecutor)webDriver;
            //刷新下页面
            jse.executeScript("window.location.reload()");
            //浏览器缩放比例
            jse.executeScript("document.body.style.zoom=1.5");
            //隐藏滚动条
            jse.executeScript("document.body.style.overflow = 'hidden'");

            // 截图并保存为文件  保存至oss
            File screenshot = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);


            String fileNameNew = "c://selenium//" + dateStr + "//" + fileName;
            //存放到本地
            FileUtils.copyFile(screenshot, new File(fileNameNew));


            return fileNameNew;

        } catch (Exception e) {
            log.error("截取图片异常！", e);
            throw new CustomException("截取图片异常！");
        } finally {
            webDriverQueue.enqueue(decorationWebDriver);
            log.info("CreditScoreService-getCreditScoreDetailImg-{}：结束截取keyNo[{}]的图片[{}]######", uuid, keyNo, webDriverQueueEnum.getCode());
        }

    }

    public Dimension getDimension(WebDriverQueueEnum webDriverQueueEnum, String keyNo) throws IOException {
        if (WebDriverQueueEnum.CREDIT_SCORE_DETAIL == webDriverQueueEnum) {
           return new Dimension(1920, 1150);
        }

        if (WebDriverQueueEnum.CREDIT_SCORE_TOP == webDriverQueueEnum) {
            return new Dimension(1920, 293);
        }

        return null;
    }

    private String dealProvinceDesc(String provinceDesc) {
        //直辖市  北京市、天津市、上海市、重庆市
        List<String> provinceGovernment = Stream.of("北京", "天津", "上海", "重庆").collect(Collectors.toList());

        if (provinceGovernment.contains(provinceDesc)) {
            return provinceDesc + "市";
        }

        //自治区 内蒙古自治区、广西自治区、西藏自治区、宁夏自治区、新疆自治区
        List<String> provinceOwn = Stream.of("内蒙古", "广西", "西藏", "宁夏", "新疆").collect(Collectors.toList());
        if (provinceOwn.contains(provinceDesc)) {
            return provinceDesc + "自治区";
        }

        return provinceDesc + "省";
    }



    /**
     * 将时间戳转换成指定格式的日期
     * @param timeStamp
     * @param pattern
     * @return
     */
    public static String convertDateStrByTimeStamp(Long timeStamp, String pattern){
        // 将毫秒时间戳转换为Instant
        Instant instant = Instant.ofEpochMilli(timeStamp);
        // 将Instant转换为LocalDateTime（注意：这将丢失时间信息）
        LocalDateTime date = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        String dateStr = date.format(formatter);

        return dateStr;
    }
}
